//
//  String+MEMore.swift
//  MESwiftExtention
//
//  Created by 朱撷潼 on 15/3/12.
//  Copyright (c) 2015年 zhuxietong. All rights reserved.
//

import Foundation
import UIKit
import Eelay

//import Regex

extension String{
    public func mobileDisplay() ->String {
        return "\(self)".replacingOccurrences(of: "|", with: " ").replacingOccurrences(of: "+", with: " ")
    }
}

extension String {
    
    public func char(at:Int) -> String {
        if at < self.count
        {
            NSMutableArray().list { (One:String, i) in
                
            }
            let s = self.index(self.startIndex, offsetBy: at)
            let e = self.index(self.startIndex, offsetBy: at+1)
            
            let subvalues = self[s..<e] // One-sided Slicing
            return String(subvalues)
        }
        return ""
    }
    

    
    //    subscript (index: Int) -> Character {
    //        return self[self.characters.index(self.startIndex, offsetBy: index)]
    //    }
    //
    //    subscript (range: Range<Int>) -> String {
    //        return String(self[self.characters.index(self.startIndex, offsetBy: range.lowerBound)..<self.characters.index(self.startIndex, offsetBy: range.upperBound)])
    //    }
    
//    public func sub(from:Int,end:Int) -> String {
//        let s = self.index(self.startIndex, offsetBy: from)
//        let e = self.index(self.startIndex, offsetBy: end)
//        
//        let subvalues = self[s..<e] // One-sided Slicing
//        return String(subvalues)
//        
//        //        return String(self[self.characters.index(self.startIndex, offsetBy: from)..<self.characters.index(self.startIndex, offsetBy: end)])
//    }
}
extension String{
    public var eelist:[[String:String]]
    {
        get{
            //            let str =
            //            """
            //        作者：爱抽烟的芭比        來源12：简书
            //        链接<age page=2>：https://www.jianshu.com/p/8b5344da29d8
            //        來源：简书
            //        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
            //        """
            
            let str = "\(self)"
            
            var new_str = str.replacingAll(matching: Regex("\\s{3,}"), with: "\n")//中间有三个空格的考虑处理为一行
            new_str = new_str.replacingAll(matching: Regex("\\s*\n\\s*"), with: "\n")
            new_str = new_str.replacingAll(matching: Regex("：\\s*"), with: ":")
            
            let lines = new_str.components(separatedBy: "\n")
            var items = [[String:String]]()
            for line in lines {
                var item =  [String:String]()
                if let title = Regex("(.+?):").firstMatch(in: line)?.captures.first as? String
                {
                    
                    item["id"] = title.replacingAll(matching: Regex("<.+>"), with: "")
                    item["value"] = line.replacingOccurrences(of: "\(title):", with: "")
                    
                    if let atrr = Regex("<(.+)>").firstMatch(in: title)?.captures.first as? String
                    {
                        var fatrr = atrr.replacingAll(matching: "\\s{2,}", with: " ")
                        fatrr = atrr.replacingAll(matching: "\\s+=\\+", with: "=")
                        let values = fatrr.components(separatedBy: " ")
                        for one in values
                        {
                            if one.contains("=")
                            {
                                let list = one.components(separatedBy: "=")
                                if list.count > 0
                                {
                                    item["\(list.first!)"] = list.last ?? ""
                                    continue
                                }
                            }
                            else{
                                item["\(one)"] = one
                            }
                        }
                    }
                    if !item.keys.contains("hidden")
                    {
                        items.append(item)
                    }
                }
                else{
                    item["value"] = line
                    items.append(item)
                }
                
            }
            return items
        }
    }
}

extension String {
    public func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false) else { return nil }
        let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
        ]
        guard let html = try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil) else { return nil }
        return html
    }
}

extension String
{
    public func contain(strings:[String]) ->Bool{
        var contain = false
        
        for one in strings {
            if self.contains(one) {
                contain = true
                break
            }
        }
        return contain
    }
}


extension String{
    public func escapeSpaceTillCahractor()->String{
        return self.stringEscapeHeadTail(["\r", " ", "\n"])
    }
    public func escapeHeader(string str:String)->(String, Bool){
        var result = self as NSString
        var findAtleastOne = false
        while( true ){
            let range = result.range(of: str)
            if range.location == 0 && range.length == 1 {
                result = result.substring(from: range.length) as NSString
                findAtleastOne = true
            }else{
                break
            }
        }
        return (result as String, findAtleastOne)
    }
    public func escapeSpaceTillCahractor(strings strs:[String])->String{
        var result = self
        while( true ){
            var findAtleastOne = false
            for str in strs {
                var found:Bool = false
                (result, found) = result.escapeHeader(string:str)
                if found {
                    findAtleastOne = true
                    break  //for循环
                }
            }
            if findAtleastOne == false {
                break
            }
        }
        return result as String
    }
    
    public func reverse()->String{
        var inReverse = ""
        for letter in self {
            inReverse = "\(letter)" + inReverse
        }
        return inReverse
    }
    
    public func escapeHeadTailSpace()->String{
        return self.escapeSpaceTillCahractor().reverse().escapeSpaceTillCahractor().reverse()
    }
    
    public func stringEscapeHeadTail(_ strs:[String])->String{
        return self.escapeSpaceTillCahractor(strings:strs).reverse().escapeSpaceTillCahractor(strings:strs).reverse()
    }
}

extension NSString{
    @objc public func escapeHeadTailSpace()->NSString{
        let str = String("\(self)").escapeHeadTailSpace()
        
        return NSString(string: str)
    }
    
    
}





extension String
{
    
    public var swift_dict:[String:Any]?{
        get{
            
            if let data = self.data(using: String.Encoding.utf8)
            {
                
                do {
                    let object = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]
                    
                    return object
                    
                } catch _ as NSError {
                    return nil
                }
            }
            return nil
        }
    }
    
    public var swift_array:[Any]?{
        get{
            
            if let data = self.data(using: String.Encoding.utf8)
            {
                
                do {
                    let object = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [Any]
                    
                    return object
                    
                } catch _ as NSError {
                    return nil
                }
            }
            return nil
        }
    }
    
    public var JsonDictionary:NSMutableDictionary?
        {
        get{
            return self.swift_dict?.mutable_dictionary
        }
    }
    
    public var JsonArray:NSMutableArray?
        {
        get{
            return self.swift_array?.mutable_array
        }
    }
    
}

extension Int
{
    
    public var cg_floatValue:CGFloat
        {
        get{
//            let value = NSString(string: "\(self)")
            return  CGFloat(self)
        }
    }
    public var num_display:String{
        get{
         if self > 100000{
            return CGFloat(self/10000).print(num: 0) + "w"
         }
         if self > 10000{
             let str = CGFloat(self/10000).print(num: 1) + "w"
            return str.replacingOccurrences(of: ".0", with: "")

         }
         if self > 1000{
            let str = CGFloat(self/1000).print(num: 1) + "k"
            return str.replacingOccurrences(of: ".0", with: "")
         }
         return "\(self)"
           
        }
    }
    
}

extension Float
{
    
    public var cg_floatValue:CGFloat
        {
        get{
            let formatter = NumberFormatter()
            formatter.groupingSeparator = ""
            formatter.decimalSeparator = "."
            formatter.numberStyle = .decimal
            formatter.formatterBehavior = .default
            if let n = formatter.number(from: "\(self)") {
                let f = CGFloat(truncating: n)
                return f
            }
           return 0
        }
    }
}

extension Double
{
    public var cg_floatValue:CGFloat
        {
        get{
            let formatter = NumberFormatter()
            formatter.groupingSeparator = ""
            formatter.decimalSeparator = "."
            formatter.numberStyle = .decimal
            formatter.formatterBehavior = .default
            if let n = formatter.number(from: "\(self)") {
                let f = CGFloat(truncating: n)
                return f
            }
           return 0
        }
    }
}


extension String
{
    
    public var cg_floatValue:CGFloat
        {
        get{
//            let value = NSString(string: self)
            let formatter = NumberFormatter()
            formatter.groupingSeparator = ""
            formatter.decimalSeparator = "."
            formatter.numberStyle = .decimal
            formatter.formatterBehavior = .default
            if let n = formatter.number(from: self) {
                let f = CGFloat(truncating: n)
                return f
            }
           return 0
        }
    }
    
    public var int_value:Int
        {
        get{
            let value = NSString(string: self)
            return Int(value.intValue)
        }
    }
    
    public var price_display:String{
        get{
            
            return self.cg_floatValue.price_display
        }
    }
}

extension CGFloat{
    public var price_display:String{
        get{
            let v = self.print(num: 2)
            if Regex("\\.[^0]0$").matches(v){
                return self.print(num: 1)
            }
            else if Regex("\\.00$").matches(v)
            {
                return self.print(num: 0)
            }
            else{
                return v
            }
        
           
        }
    }
}


